package com.hjxr.quota.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ConnectionPool {
    private static Logger logger = LoggerFactory.getLogger(ConnectionPool.class);

    private final String driverClassName = "oracle.jdbc.driver.OracleDriver";
    private final String url = "jdbc:oracle:thin:@192.168.168.105:1521:orcl";
    private final String username = "HSQY";
    private final String password = "czsb*1234";
    List<Connection> cs = new ArrayList<Connection>();
    private int size;
    private volatile static ConnectionPool connectionPool = null;

    public static ConnectionPool getConnectionPool() {
        if (connectionPool == null) {
            synchronized (ConnectionPool.class) {
                if (connectionPool == null) {
                    connectionPool = new ConnectionPool(2);
                }
            }
        }
        return connectionPool;
    }

    private ConnectionPool(int size) {
        this.size = size;
        init();
    }

    public void init() {
        try {
            Class.forName(driverClassName);
            for (int i = 0; i < size; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                cs.add(connection);
            }

        } catch (ClassNotFoundException classNotFoundException) {
            logger.error("init connectPool: ", classNotFoundException);
        } catch (SQLException sqlException) {
            logger.error("init connectPool: ", sqlException);
        }
    }

    public synchronized Connection getConnection() {
        while (cs.isEmpty()) {
            try {
                // 如果连接池中没有连接可用则等待
                this.wait();
            } catch (InterruptedException e) {
                logger.error("getConnection get error:", e);
            }
        }
        Connection connection = cs.remove(0);
        return connection;
    }

    public synchronized void freeConnection(Connection c) {
        // 使用完给回连接池中
        cs.add(c);
        // 唤醒wait告诉它有新的连接池可用
        this.notifyAll();
    }
}
